<template>
  <el-menu-item index="6" @click="activeDraw"> 发布公告</el-menu-item>
  <div class="Announcement-information-container" v-if="isClose">
    <!-- header -->
    <div class="Announcement-information-header">
      <h2>公告信息</h2>
      <img
        class="close"
        src="@/images/close.png"
        alt=""
        @click="isClose = false"
      />
    </div>
    <!-- body -->
    <div class="Announcement-information-body">
      <!-- title -->
      <div class="title">发布公关的区域与物业电话</div>
      <!--btn-->
      <div class="Announcement-information-body-btn">
        <input
          type="text"
          placeholder="请输入关键词"
          v-model.trim="searchKey"
          @keyup.enter="handleSearch"
        />
        <div class="icon-container" @click="handleSearch">
          <i class="iconfont icon-zhongzhi"></i>
        </div>
        <div class="icon-container">
          <i class="iconfont icon-biaogedaochu" @click="handleExport"></i>
        </div>
      </div>
      <!-- table -->
      <div class="Announcement-information-body-table">
        <table class="table">
          <thead>
            <tr>
              <th>区域名称</th>
              <th>物业电话</th>
            </tr>
          </thead>
          <tbody
            class="tbody"
            v-for="(item, index) in overlapAreaAttr"
            :key="index"
          >
            <tr>
              <td>{{ item.name }}</td>
              <td>{{ item.phone }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <!-- information -->
    <div class="Announcement-information-information">
      <span>公告信息：</span>
      <textarea
        placeholder="请输入公告信息"
        v-model.trim="anncInformation"
      ></textarea>
    </div>
    <!-- bottom -->
    <div class="Announcement-information-bottom">
      <button class="affirm" @click="handleAnncInformation">确认</button>
      <button @click="isClose = false">取消</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, watch } from "vue";
import { createDraw } from "@/api/ol-api/createDraw.js";
import {
  setLineStyle,
  setAreaStyle,
  FeatureToJson,
  JsonToFeature,
} from "@/api/ol-api/index";
import { Query } from "@/api/mapgis-api/Query";
import { useTrafficStore } from "@/stores/traffic";
import * as XLSX from "xlsx";
let map; // 定义 map 变量
let overlapAreaAttr = ref([]); // 重合的居民区属性
let overlapAreaAttr_ = ref([]); // 重合的居民区属性
const searchKey = ref(""); // 搜索关键字
let isClose = ref(false); // 关闭标志
const anncInformation = ref(""); // 公告信息
const $store = useTrafficStore(); // 引入 store

/* 线画笔-->缓冲区分析-->缓冲区域与居民区进行叠加分析 */
//设置缓冲区图层
const bufferLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [],
  }),
  style: new ol.style.Style({
    fill: new ol.style.Fill({
      color: "rgba(255, 255, 0, 0.8)",
    }),
    stroke: new ol.style.Stroke({
      color: "yellow",
      width: 2,
    }),
  }),
  zIndex: 999,
});
/* 设置画布 */
const source = new ol.source.Vector({
  features: [],
});
const layer = new ol.layer.Vector({
  source,
  style: setLineStyle({ color: "red", width: 2 }),
  zIndex: 1000,
});
/* 创建一个线画笔 */
let draw = createDraw({
  type: "LineString",
  source,
  success: async (feature) => {
    map.removeInteraction(draw);
    layer.getSource().clear();
    bufferLayer.getSource().clear();
    source.clear();
    const geometry = feature.getGeometry();
    source.addFeatures(geometry);
    // console.log(geometry, "geometry");
    //缓冲区分析
    const lineCoordinates = feature.getGeometry().getCoordinates();
    const line = turf.lineString(lineCoordinates);
    const buffer = turf.buffer(line, 0.05);
    //这里获取到的buffer是genjson格式,转化为olfeature格式
    const bufferFeature = new ol.format.GeoJSON().readFeatures(buffer);
    bufferLayer.getSource().addFeatures(bufferFeature);

    /* 叠加分析  buffer,residentialArea*/
    //获取mapgis的居民区数据
    let service = {
      docName: "guanggu",
      layerId: 0,
    };
    let features = await Query.queryByLayerId(service);

    console.log("查询结果", features);
    const residentialArea = FeatureToJson(features).features;
    //叠加分析判断是否重合,选取重合的居民区,获取数据
    const overlapArea = residentialArea.filter((item) => {
      if (turf.booleanOverlap(buffer, item)) {
        return item;
      }
    });
    console.log(overlapArea, "overlapArea");
    //获取重合的居民区名称和物业电话
    overlapAreaAttr_.value = overlapArea.map((item) => ({
      name: item.properties.values_.name,
      phone: item.properties.values_.tel,
    }));
    //保存一个未修改的原始属性
    overlapAreaAttr.value = overlapAreaAttr_.value;
    if (overlapAreaAttr.value.length > 0) {
      isClose.value = !isClose.value;
    }
  },
});

onMounted(async () => {
  const { proxy } = getCurrentInstance();
  map = proxy.$map;
  map.addLayer(layer);
  map.addLayer(bufferLayer);

});

//点击一次激活画笔,第二次清除所有数据
async function activeDraw() {
  /* 激活画笔 */
  map.addInteraction(draw);
  layer.getSource().clear();
}

//搜索功能
const handleSearch = () => {
  //搜索关键词检索
  if (searchKey.value) {
    overlapAreaAttr.value = overlapAreaAttr.value.filter(
      (item) =>
        item.name.includes(searchKey.value) ||
        item.phone.includes(searchKey.value)
    );
  } else {
    overlapAreaAttr.value = overlapAreaAttr_.value;
  }
};

//发布公告功能,把发布公告存储下来,然后发送给后台
const handleAnncInformation = () => {
  //获取公告信息
  if (anncInformation.value) {
    //存储公告信息
    $store.addAnnouncement({
      time: new Date().toLocaleString(),
      announcement: anncInformation.value,
    });
    isClose.value = false;
  }
  console.log("发布公告成功", anncInformation.value);
};

//写一个监听事件,如果isClose为false,则清除所有图层数据
watch(isClose, (newVal) => {
  if (!newVal) {
    //清除所有图层数据
    layer.getSource().clear();
    bufferLayer.getSource().clear();
    source.clear();
  }
});

/* 导出excel表 */
const handleExport = () => {
  //表格的引用 文件标题 导出的文件名
  const table = document.querySelector(".table");
  // 将表格转成工作表
  const ws = XLSX.utils.table_to_sheet(table);
  // 创建一个新的工作簿
  const wb = XLSX.utils.book_new();
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, "路况信息");
  // 导出为 Excel 文件
  XLSX.writeFile(wb, "路况信息表.xlsx");
};
</script>

<style scoped>
.Announcement-information-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 420px;
  width: 420px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin: 0 auto;
  border-radius: 5px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
  background-color: white;
}
/* header */
.Announcement-information-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
}
.Announcement-information-header img {
  width: 12px;
  height: 12px;
  margin-right: 20px;
  cursor: pointer;
}
.Announcement-information-header h2 {
  padding: 10px;
  color: gray;
}
/* body */
.Announcement-information-body {
  width: 95%;
  margin: 0 auto;
  border: 1px solid #ccc;
}
.Announcement-information-body .title {
  background-color: #f2f2f2;
  padding: 5px;
  color: gray;
}
/* body--btn */
.Announcement-information-body-btn {
  display: flex;
  justify-content: right;
  align-items: center;
  margin: 10px 0;
}
.Announcement-information-body-btn input {
  width: 200px;
  height: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  outline: none;
}
.Announcement-information-body-btn input::placeholder {
  color: #ccc;
  font-size: 13px;
}
.Announcement-information-body-btn div {
  height: 20px;
  width: 30px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 10px;
  cursor: pointer;
}
.Announcement-information-body-btn div:hover {
  background-color: rgba(210, 232, 241, 0.3);
}

.icon-container i {
  color: black; /* 默认颜色 */
  transition: color 0.1; /* 添加平滑过渡效果 */
}
.Announcement-information-body-btn div:hover.icon-container i {
  color: rgba(64, 158, 255, 1); /* 鼠标悬停时的颜色 */
  z-index: 100;
}
.Announcement-information-body-btn input:focus {
  border-color: #409eff; /* 聚焦时的边框颜色 */
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5); /* 聚焦时的阴影效果 */
}
/* table */
.Announcement-information-body-table {
  height: 120px;
  overflow: auto;
}
.Announcement-information-body-table table {
  width: 100%;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid #ccc;
}
.Announcement-information-body-table th {
  text-align: center;
  padding: 5px 10px;
  border: 1px solid #ccc;
  background-color: white;
  /*   position: sticky; 
  top: 0;  */
}
.Announcement-information-body-table td {
  text-align: center;
  border: 1px solid #ccc;
  padding: 5px;
}
.Announcement-information-body-table tbody {
  font-size: 13px;
}
.Announcement-information-body-table tbody tr:nth-child(odd) {
  background-color: #f2f2f2;
}
/* information */
.Announcement-information-information {
  display: flex;
  justify-content: center;
  margin: 10px 0;
}
.Announcement-information-information span {
  font-weight: bold;
}

.Announcement-information-information textarea {
  width: 70%; /* 设置宽度 */
  height: 55px; /* 设置高度 */
  resize: none; /* 禁止调整大小（可选） */
  padding: 10px; /* 添加内边距（可选） */
  border: 1px solid #ccc; /* 边框样式（可选） */
  border-radius: 4px; /* 边角圆润（可选） */
  outline: none;
}
.Announcement-information-information textarea:focus {
  border-color: #409eff; /* 聚焦时的边框颜色 */
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5); /* 聚焦时的阴影效果 */
}
.Announcement-information-information textarea::placeholder {
  font-size: 13px;
  color: #ccc;
}
/* bottom */
.Announcement-information-bottom {
  height: 50px;
  width: 100%;
  border-top: 1px solid #ccc;
  text-align: right;
}
.Announcement-information-bottom button {
  padding: 8px 15px;
  margin: 10px;
  border: 1px solid #ccc;
  background-color: #f0f0f0; /* 背景颜色 */
  cursor: pointer; /* 鼠标悬停时显示为指针 */
  border-radius: 5px;
}
.Announcement-information-bottom button.affirm {
  background-color: #347bb7;
  color: white;
}
</style>
